<?php

namespace app\api\controller\admin;

use app\admin\model\Admin;
use app\admin\model\dts\activity\Notes;
use app\admin\model\dts\Meeting;
use app\common\controller\TApi;
use think\Db;
use app\common\exception\UploadException;
use app\common\library\Upload;
use DateTime;
use Exception;
use OSS\OssClient;
use think\Collection;

/**
 * 职工端接口
 */
class Index extends TApi
{
    protected $noNeedLogin = ['upload'];
    protected $noNeedRight = ['*'];

    public function upload() {
        $attachment = null;
        
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

        //检测删除文件或附件
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            //如果设定为不备份则删除文件和记录 或 强制删除
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($upload) {
                    //文件绝对路径
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };

        //文件绝对路径
        $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
        try {
            $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
            //成功不做任何操作
        } catch (\Exception $e) {
            $checkDeleteFile($attachment, $upload, true);
            \think\Log::write($e->getMessage());
            $this->error("上传失败(1002)");
        }
        $checkDeleteFile($attachment, $upload);

        // 记录云存储记录
        $data = $attachment->toArray();
        \app\common\model\Attachment::where('id', $data['id'])->update(['storage' => 'alioss']);

        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

    //待办事项总量
    public function todoItemNum() {
        $admin = $this->auth->getAdmininfo();

        $num = Db::name('dts_todo_items')->where(['admin_id' => $admin['id'], 'status' => 0])->count(1);

        $this->success('success', ['num' => $num]);
    }

    //待办事项分类数量
    public function todoItemList() {
        $admin = $this->auth->getAdmininfo();
        
        $list = Db::name('dts_todo_items')->field('category,count(1) as num')->where(['admin_id' => $admin['id'], 'status' => 0])->group('category')->select();

        $this->success('success', $list);
    }

    //通知信息数量
    public function gardenNoticeNum() {
        $admin = $this->auth->getAdmininfo();

        $query1 = 'FIND_IN_SET('.$admin['id'].',teacher_notice_range) > 0';
        $num1 = Db::name('dts_garden_notice')->whereRaw($query1)->count(1);

        $query2 = 'FIND_IN_SET('.$admin['id'].',teacher_read_range) > 0';
        $num2 = Db::name('dts_garden_notice')->whereRaw($query2)->count(1);

        $num = $num1 - $num2;

        $this->success('success', ['num' => $num > 0 ? $num : 0]);
    }

    //-------------------------------------------------------------------------------------------------------------------------------------------

    //考勤统计
    public function attendanceTotal() {
        $admin = $this->auth->getAdmininfo();

        $starttime = $this->request->get('starttime');
        $endtime = $this->request->get('endtime');

        $query = ['admitGuid' => $admin['admitGuid'], 'showTime' => ['between', [strtotime($starttime), strtotime($endtime)]]];
        $attendance = Db::name('dts_attendance_log')->where($query)->group("FROM_UNIXTIME(showTime,'%Y-%m-%d')")->select();
        
        $time = time();
        if(strtotime($endtime) - $time >= 0) {
            $endtime = date('Y-m-d H:i:s', $time);
        }
        $diff = date_diff(new DateTime($endtime), new DateTime($starttime));
        $days = intval($diff->format("%a")) + 1;
        $missing = 0;
        if(strtotime($starttime) - $time <= 0) {
            $missing = $days - sizeof($attendance);
        }
        
        $list = ['attendance' => sizeof($attendance), 'belate' => 0, 'missing' => $missing];

        $this->success('success', $list);
    }

    //考勤列表
    public function attendanceList() {
        
        $starttime = $this->request->get('starttime');
        $endtime = $this->request->get('endtime');
        $query = ['log.showTime' => ['between', [strtotime($starttime), strtotime($endtime)]]];

        $list = Db::name('dts_attendance_log')->alias('log')
        ->field("dept.name as deptname,position.name as position,admin.position_ids,log.admitName,FROM_UNIXTIME(MIN(log.showTime), '%Y-%m-%d %H:%i') as mintime,FROM_UNIXTIME(MAX(log.showTime), '%Y-%m-%d %H:%i') as maxtime")
        ->join('admin admin', 'admin.admitGuid=log.admitGuid', 'left')
        ->join('dts_dept dept', 'dept.id=admin.dept_id', 'left')
        ->join('dts_config_position position', 'FIND_IN_SET(position.id,admin.position_ids)', 'left')
        ->where($query)
        ->group("FROM_UNIXTIME(log.showTime,'%Y-%m-%d'),log.admitName")
        ->select();

        foreach($list as $items) {

        }

        $this->success('success', $list);
    }

    //考勤记录
    public function attendanceLog() {
        $admin = $this->auth->getAdmininfo();

        $starttime = $this->request->get('starttime');
        $endtime = $this->request->get('endtime');
        $query = ['admitGuid' => $admin['admitGuid'], 'showTime' => ['between', [strtotime($starttime), strtotime($endtime)]]];
        $type = $this->request->get('type');
    
        $model = Db::name('dts_attendance_log')->field('id,FROM_UNIXTIME(showTime,"%Y-%m-%d") as days,FROM_UNIXTIME(showTime,"%Y-%m-%d %H:%i:%s") as createtime')->where($query);

        if($type == 0) {//考勤
            $list = $model->order('showTime', 'asc')->select();
        }

        if($type == 1) {//迟到
            $list = [];
        }

        if($type == 2) {//缺失
            $time = time();
            if(strtotime($endtime) - $time >= 0) {
                $endtime = date('Y-m-d H:i:s', $time);
            }
            $map = new Collection();
            for ($time = strtotime($starttime); $time <= strtotime($endtime);) {
                $key = date("Y-m-d", $time);
                $map[$key] = $key;
                $time += 86400;
            }
            
            $list = $model->group("FROM_UNIXTIME(showTime,'%Y-%m-%d')")->order('showTime', 'asc')->select();
            foreach($list as $items) {
                if($map->offsetExists($items['days'])) {
                    $map->offsetUnset($items['days']);
                }
            }

            $list = [];
            $data = array_values($map->toArray());
            foreach($data as $item) {
                $list[] = ['createtime' => $item];
            }
        }

        $this->success('success', $list);
    }

    //考勤打卡
    public function attendanceCheck() {

        $admin = $this->auth->getAdmininfo();
    }

    //通知信息
    public function gardenNotice() {

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $type = $this->request->get('type');
        $title = $this->request->get('title');

        $admin = $this->auth->getAdmininfo();
        
        $service = new \app\api\controller\Service;
        $list = $service->gardenNotice($admin, 1, $type, $title, $page, $pagesize);

        $this->success('success', $list);
    }

    //通知详情
    public function gardenNoticeInfo() {

        $id = $this->request->get('id');

        $admin = $this->auth->getAdmin();
        
        $service = new \app\api\controller\Service;
        $data = $service->gardenNoticeInfo($admin, 1, $id);

        if($data) {
            $teacherArr1 = explode(',', $data['teacher_notice_range']);
            $teacherArr2 = explode(',', $data['teacher_read_range']);
            $teacherArr = array_unique(array_diff($teacherArr1, $teacherArr2));
            $data['teacherNum'] = sizeof($teacherArr);
            $data['teacherStr'] = Db::name('admin')->where('id', 'in', $teacherArr)->value('GROUP_CONCAT(DISTINCT nickname)');
    
            $parentArr1 = explode(',', $data['parent_notice_range']);
            $parentArr2 = explode(',', $data['parent_read_range']);
            $parentArr = array_unique(array_diff($parentArr1, $parentArr2));
            $data['parentNum'] = sizeof($parentArr);
            $data['parentStr'] = Db::name('user')->alias('user')
            ->join('dts_student stu', 'stu.user_mobile = user.mobile', 'left')
            ->where('user.id', 'in', $parentArr)
            ->value('GROUP_CONCAT(DISTINCT stu.username,stu.relationship)');

            $data['allNum'] = sizeof(explode(',', $data['push_text']));
        }


        $this->success('success', $data);
    }

    //发布通知
    public function releaseNotice() {

        $title = $this->request->post('title');
        $content = $_POST['content'];
        $files = $this->request->post('files');
        $files_json = $this->request->post('files_json');
        $push_text = $this->request->post('push_text');
        $teacherIds = $this->request->post('teacherIds');
        $teacher_json = $this->request->post('teacher_json');
        $studentIds = $this->request->post('studentIds');
        $student_json = $this->request->post('student_json');

        if(!$title || !$content || !$push_text || (!$teacherIds && !$studentIds)) {
            $this->error('请填写通知内容');
        }

        $parentIds = '';
        if($studentIds) {
            $arrIds = array_map('intval', explode(',', $studentIds));
            $tempArr = Db::name('dts_student')->where('id', 'in', $arrIds)->select();
            $parentIds = join(',', array_column((array)$tempArr, 'user_id'));
        } 

        $admin = $this->auth->getAdmin();
        $data = [
            'title' => $title, 'content' => $content, 'push_text' => $push_text, 'files' => $files,
            'teacher_notice_range' => $teacherIds, 'teacher_json' => $teacher_json, 'student_notice_range' => $studentIds, 
            'student_json' => $student_json, 'parent_notice_range' => $parentIds, 'admin_id' => $admin['id']
        ];

        if($files_json) {
            $data['files_json'] = html_entity_decode($files_json);
        }

        \app\admin\model\dts\garden\Notice::create($data);

        $this->success('success');
    }

    //删除通知
    public function delNotice() {
        $noticeIds = $this->request->post('noticeIds/a');
        if(!$noticeIds) {
            $this->error('请选择要删除的通知');
        }
        $noticeModel = new \app\admin\model\dts\garden\Notice;
        $noticeModel->where('id', 'in', $noticeIds)->delete();

        $this->success('success');
    }

    //班级活动
    public function classesActivity() {

        $gradeId = $this->request->get('gradeId');
        $classesId = $this->request->get('classesId');
        $starttime = $this->request->get('starttime');
        $endtime = $this->request->get('endtime');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $admin = $this->auth->getAdmininfo();

        //权限判断
        $isAuth = $this->auth->isAdmin();
        if(!$isAuth) {
            $url = 'api/admin/index/activity';
            $isAuth = $this->auth->check($url);
        }

        $service = new \app\api\controller\Service;
        $list = $service->classesActivity($admin, 1, $isAuth, $gradeId, $classesId, $starttime, $endtime, $page, $pagesize);

        $this->success('success', $list);
    }

    //增加或编辑活动
    public function addClassesActivity() {
        $classesId = $this->request->post('classesId');
        $title = $this->request->post('title');
        $describes = $this->request->post('describes');
        $images = $this->request->post('images');

        if(!$classesId || !$title || !$describes || !$images) {
            $this->error('请填写活动内容');
        }

        $admin = $this->auth->getAdmininfo();
        $data = ['classes_id' => $classesId, 'title' => $title, 'describes' => $describes, 'images' => $images, 'createby' => $admin['nickname'], 'createtime' => time()];

        $activityId = $this->request->post('activityId');
        if($activityId) {
            \app\admin\model\dts\classes\Activity::where('id', $activityId)->update($data);
        }else {
            \app\admin\model\dts\classes\Activity::create($data);
        }

        $this->success('success');
    }

    //删除活动
    public function delClassesActivity() {

        $params = $this->request->post('params/a');//['id' => '活动Id', 'images' => '删除后的图片']
        if(!$params) {
            $this->error('请选择要删除的活动');
        }
        $activityModel = new \app\admin\model\dts\classes\Activity;

        foreach($params as $item) {
            $images = $item['images'];
            if($images) {
                $activity = $activityModel->where('id', $item['id'])->find();
                if($activity) {
                    $arrImgs = explode(',', $activity['images']);
                    $result = array_diff($arrImgs, [$images]);
                    $activityModel->where('id', $item['id'])->update(['images' => join(',', $result)]);
                }
            }else {
                $activityModel->where('id', 'in', $item['id'])->delete();
            }
        }

        $this->success('success');
    }

    //圆周计划
    public function yuanzhouPlan() {
        $startdate = $this->request->get('startdate');
        $enddate = $this->request->get('enddate');

        if(!$startdate || !$enddate) {
            $this->error('请提交查询时间');
        }

        $data = Db::name('dts_plan_yuanzhou')->where(['startdate' => $startdate, 'enddate' => $enddate])->find();

        $this->success('success', $data);
    }

    //圆周计划详情
    public function yuanzhouPlanInfo() {
        $palnId = $this->request->get('planId');

        $info = Db::name('dts_plan_yuanzhou')->where('id', $palnId)->find();

        $this->success('success', $info);
    }

    //增加或编辑圆周计划
    public function addYuanzhouPlan() {

        $which_week = $this->request->post('which_week');
        $startdate = $this->request->post('startdate');
        $enddate = $this->request->post('enddate');
        $keynote = $this->request->post('keynote');
        $content = $this->request->post('content/a');
        $other_work = $this->request->post('other_work');

        if(!$which_week || !$startdate || !$enddate || !$keynote || !$content) {
            $this->error('请填写圆周计划内容');
        }
        $admin = $this->auth->getAdmininfo();
        $data = ['which_week' => $which_week, 'startdate' => $startdate, 'enddate' => $enddate,
                 'keynote' => $keynote, 'content' => json_encode($content, JSON_UNESCAPED_UNICODE), 'other_work' => $other_work,
                 'createby' => $admin['nickname'], 'createtime' => time()];

        $planId = $this->request->post('planId');
        if($planId) {
            \app\admin\model\dts\plan\Yuanzhou::where('id', $planId)->update($data);
        }else {
            \app\admin\model\dts\plan\Yuanzhou::create($data);
        }
        
        $this->success('success');
    }

    //教学计划
    public function teachingPlan() {
        $startdate = $this->request->get('startdate');
        $enddate = $this->request->get('enddate');
    
        if(!$startdate || !$enddate) {
            $this->error('请提交查询时间');
        }

        $gradeId = $this->request->get('gradeId');
        $classesId = $this->request->get('classesId');
        if(!$gradeId) {
            $data = Db::name('dts_classes')->alias('dc')
                ->field('dpt.*,dc.name as classname')
                ->join([
                    ['dts_plan_teaching dpt', 'dpt.classes_id = dc.id and dpt.startdate = "'.$startdate.'" and dpt.enddate = "' . $enddate  .'"', 'left']
                ])
                ->where(['dc.id' => $classesId])
                ->find();
        }else {
            $page = $this->request->get('page', 1);
            $pagesize = $this->request->get('pagesize', 5);

            $data = Db::name('dts_plan_teaching')->alias('dpt')
            ->field('dpt.which_week,dpt.startdate,dpt.enddate,dc.name as classname')
            ->join([
                ['dts_classes dc', 'dc.id = dpt.classes_id', 'left']
            ])
            ->where(['dc.grade_id' => $gradeId, 'dc.id' => $classesId])
            ->order('dpt.createtime', 'desc')
            ->paginate($pagesize, false, ['page' => $page]);
        }

        $this->success('success', $data);
    }

    //教学计划详情
    public function teachingPlanInfo() {
        $palnId = $this->request->get('planId');

        $info = Db::name('dts_plan_teaching')->alias('dpt')
        ->field('dpt.*,dc.name as classname')
        ->join([
            ['dts_classes dc', 'dc.id = dpt.classes_id']
        ])
        ->where('dpt.id', $palnId)
        ->find();

        $this->success('success', $info);
    }

    //增加或编辑教学计划
    public function addTeachingPlan() {
        $which_week = $this->request->post('which_week');
        $startdate = $this->request->post('startdate');
        $enddate = $this->request->post('enddate');
        $classesId = $this->request->post('classesId');
        $content = $this->request->post('content/a');

        if(!$which_week || !$startdate || !$enddate || !$classesId || !$content) {
            $this->error('请填写圆周计划内容');
        }

        $admin = $this->auth->getAdmininfo();
        $data = ['which_week' => $which_week, 'startdate' => $startdate, 'enddate' => $enddate,
                 'classes_id' => $classesId, 'content' => json_encode($content, JSON_UNESCAPED_UNICODE), 'createby' => $admin['nickname'], 'createtime' => time()];

        $planId = $this->request->post('planId');
        if($planId) {
            \app\admin\model\dts\plan\Teaching::where('id', $planId)->update($data);
        }else {
            \app\admin\model\dts\plan\Teaching::create($data);
        }
        
        $this->success('success');
    }

    //会议记录
    public function meetingLog() {
        $query = []; $queryRaw = '';

        $type = $this->request->get('type');
        $name = $this->request->get('name');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $admin = $this->auth->getAdmininfo();
        if(!$type) {
            $query = ['dm.status' => Meeting::status_1, 'dm.is_record' => Meeting::is_record_1];
            $queryRaw = 'FIND_IN_SET('.$admin['id'].',dm.visible_admin_ids) > 0 OR dm.visible_admin_ids is NULL';
        }else {
            $query = ['dm.status' => Meeting::status_1, 'dm.record_id' => $admin['id']];
        }
        $query1 = $name ? ['dm.name' => ['LIKE', '%' . $name . '%']] : [];

        $dbmodel = Db::name('dts_meeting')->alias('dm')
        ->field('dm.id,dm.name,dm.startdate,dm.enddate,dm.is_record,dm.record_id,record.nickname as recordname,FROM_UNIXTIME(dm.record_time,"%Y-%m-%d %H:%i") as record_time')
        ->join([
            ['admin record', 'record.id = dm.record_id', 'left']
        ])
        ->where($query);
        
        if($queryRaw) {
            $dbmodel = $dbmodel->whereRaw($queryRaw);
        }
        if($query1) {
            $dbmodel = $dbmodel->where($query1);
        }

        $list = $dbmodel->order('dm.createtime', 'desc')->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //记录会议
    public function recordMeeting() {
        $meetingId = $this->request->post('meetingId');
        $context = $this->request->post('context');
        $files = $this->request->post('files');
        $files_json = $this->request->post('files_json');
        $adminIds = $this->request->post('adminIds');
        $admin_json = $this->request->post('admin_json');
        if(!$meetingId || !$context) {
            $this->error('请填写会议内容');
        }

        $data = ['record_context' => $context, 'record_files' => $files, 'record_time' => time(), 'visible_admin_ids' => $adminIds, 'visible_admin_json' => $admin_json, 'is_record' => Meeting::is_record_1];
        if($files_json) {
            $data['record_files_json'] = html_entity_decode($files_json);
        }

        \app\admin\model\dts\Meeting::where('id', $meetingId)->update($data);

        $this->success('success');
    }

    //会议详情
    public function meetingInfo() {
        $meetingId = $this->request->get('meetingId');

        if(!$meetingId) {
            $this->error('未查询到会议详情');
        }

        $info = Db::name('dts_meeting')->alias('dm')
        ->field('dm.*,FROM_UNIXTIME(dm.record_time,"%Y-%m-%d %H:%i") as record_time,FROM_UNIXTIME(dm.createtime,"%Y-%m-%d %H:%i") as createtime,dcm.name as dcmname,GROUP_CONCAT(DISTINCT involve.nickname) as involvename,examine.nickname as examinename,record.nickname as recordname,GROUP_CONCAT(DISTINCT visible.nickname) as visiblenames,create.nickname as createname,GROUP_CONCAT(DISTINCT copy.nickname) as copyname')
        ->join([
            ['dts_config_meeting dcm', 'dcm.id = dm.config_meeting_id', 'left'],
            ['admin involve', 'FIND_IN_SET(involve.id,dm.involved_ids)', 'left'],
            ['admin examine', 'examine.id = dm.examine_id', 'left'],
            ['admin record', 'record.id = dm.record_id', 'left'],
            ['admin visible', 'FIND_IN_SET(visible.id,dm.visible_admin_ids)', 'left'],
            ['admin create', 'create.id = dm.create_id', 'left'],
            ['admin copy', 'FIND_IN_SET(copy.id,dm.copy_ids)', 'left'],
        ])
        ->where('dm.id', $meetingId)
        ->group('dm.id')
        ->find();

        $apiService = new \app\api\controller\Service;
        $admin = $this->auth->getAdmininfo();
        $apiService->handletodoitembyapprove($info['id'], $admin['id']);
        
        $this->success('success', $info);
    }

    //会议列表
    public function meetingList() {

        $type = $this->request->get('type');
        $name = $this->request->get('name');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $queryOrRaw = '';
        $admin = $this->auth->getAdmininfo();
        if($type) {
            $query = ['dm.examine_id' => $admin['id']];
            $queryOrRaw = 'dm.status = '.Meeting::status_1.' and FIND_IN_SET('.$admin['id'].', dm.copy_ids) > 0';
        }else {
            $query = ['dm.create_id' => $admin['id']];
        }
        $query1 = $name ? ['dm.name' => ['LIKE', '%' . $name . '%']] : [];

        $dbmodel = Db::name('dts_meeting')->alias('dm')
        ->field('dm.id,dm.name,dm.startdate,dm.enddate,dm.status,dm.examine_id,dm.copy_ids,dcm.name as dcmname,record.nickname as recordname')
        ->join([
            ['dts_config_meeting dcm', 'dcm.id = dm.config_meeting_id', 'left'],
            ['admin record', 'record.id = dm.record_id', 'left'],
        ])
        ->where(array_merge($query, $query1));
        if($queryOrRaw) {
            $dbmodel = $dbmodel->whereOrRaw($queryOrRaw);
        }
        
        $list = $dbmodel->order('dm.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //预约会议
    public function preMeeting() {

        $name = $this->request->post('name');
        $startdate = $this->request->post('startdate');
        $enddate = $this->request->post('enddate');
        $config_meeting_id = $this->request->post('config_meeting_id');
        $involved_ids = $this->request->post('involved_ids');
        $involved_json = $this->request->post('involved_json');
        $annex = $this->request->post('annex');
        $annex_json = $this->request->post('annex_json');
        $remark = $this->request->post('remark');
        $record_id = $this->request->post('record_id');
        
        if(!$name || !$startdate || !$enddate || !$config_meeting_id || !$involved_ids || !$record_id) {
            $this->error('请填写预约内容');
        }

        $configMeeting = Db::name('dts_config_meeting')->where('id', $config_meeting_id)->find();
        if(!$configMeeting) {
            $this->error('未查询到会议室');
        }

        $num = $this->isPreMeeting($startdate, $enddate, $config_meeting_id);
        if($num) {
            $this->error('会议室正在使用中');
        }

        $admin = $this->auth->getAdmininfo();
        $data = [
            'name' => $name, 'startdate' => $startdate, 'enddate' => $enddate, 'config_meeting_id' => $config_meeting_id,
            'involved_ids' => $involved_ids, 'involved_json' => $involved_json, 'remark' => $remark, 
            'examine_id' => $configMeeting['examine_id'], 'record_id' => $record_id, 'create_id' => $admin['id']
        ];
        if($annex) {
            $data['annex'] = $annex;
            $data['annex_json'] = html_entity_decode($annex_json);
        }

        $db = \app\admin\model\dts\Meeting::create($data);
        $createData = $db->getData();
        //发送公众号消息
        $apiService = new \app\api\controller\Service;
        $apiService->savetodoitem('预约会议', 'meeting', $configMeeting['examine_id'], $createData['id']);
        $thing12 = isset($name) ? mb_substr($name, 0, 20, 'utf-8') : '';
        $weChatData1 = ['phrase4' => '预约会议', 'thing12' => $thing12, 'thing21' => $admin['nickname'], 'time3' => $startdate];
        $apiService->wechatmessage($data['examine_id'], $apiService->template1, $apiService->jumpUrl('meeting').'?id='.$createData['id'], $weChatData1);

        $this->success('success');
    }

    private function isPreMeeting($startdate, $enddate, $config_meeting_id) {

        $num = \app\admin\model\dts\Meeting::where(['config_meeting_id' => $config_meeting_id, 'status' => Meeting::status_1])->whereRaw("enddate >= '".$startdate."'")->count(1);
        return $num;
    }

    //会议审批
    public function examineMeeting() {

        $meetingId = $this->request->post('meetingId');
        $status = $this->request->post('status');
        $refuse = $this->request->post('refuse', '');

        if(!$meetingId || !in_array(intval($status), [Meeting::status_1, Meeting::status_2])) {
            $this->error("请选择审批结果");
        }
        $meeting = \app\admin\model\dts\Meeting::where('id', $meetingId)->find();
        if(!$meeting) {
            $this->error("为查询到审批的会议");
        }
        $num = $this->isPreMeeting($meeting['startdate'], $meeting['enddate'], $meetingId);
        if($num) {
            $this->error('会议室正在使用中');
        }
        $admin = $this->auth->getAdmininfo();
        if($meeting['examine_id'] != $admin['id']) {
            $this->error('审批人不一致');
        }

        $data = ['status' => $status, 'refuse' => $refuse];
        if($status == Meeting::status_1) {
            $config = \app\admin\model\dts\config\Meeting::where('id', $meeting['config_meeting_id'])->find();
            if($config) {
                $data['copy_ids'] = $config['copy_ids'];
            }
        }

        \app\admin\model\dts\Meeting::where('id', $meetingId)->update($data);
        //发送待办事项，公众号消息
        $apiService = new \app\api\controller\Service;
        $apiService->savetodoitem('会议审批', 'meeting', $meeting['create_id'], $meeting['id']);
        $thing12 = isset($name) ? mb_substr($name, 0, 20, 'utf-8') : '';
        $weChatData2 = ['phrase4' => '会议审批', 'thing12' => $thing12, 'thing16' => $admin['nickname'], 'time15' => date("Y-m-d H:i:s", time())];
        $apiService->wechatmessage($meeting['create_id'], $apiService->template2, $apiService->jumpUrl('meeting').'?id='.$meetingId, $weChatData2);
        if(isset($data['copy_ids'])) {//抄送
            $copyArr = explode(',', $data['copy_ids']);
            foreach($copyArr as $id) {
                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl('meeting').'?id='.$meetingId, $weChatData2);
            }
        }

        $this->success('success');
    }
    
    //会议删除
    public function delMeeting() {
        $meetingId = $this->request->post('meetingId');
        if(!$meetingId) {
            $this->error('请选择删除的会议');
        }

        \app\admin\model\dts\Meeting::where('id', $meetingId)->delete();

        $this->success('success');
    }

    //活动小记
    public function activityNotes() {

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $type = $this->request->get('type');
        
        $gradeId = $this->request->get('gradeId');
        $studentId = $this->request->get('studentId');
        $classesId = $this->request->get('classesId');
        $realmId = $this->request->get('realmId');
        $labelId = $this->request->get('labelId');

        $admin = $this->auth->getAdmininfo();

        //权限判断
        $isAuth = $this->auth->isAdmin();
        if(!$isAuth) {
            $url = 'api/admin/index/notes';
            $isAuth = $this->auth->check($url);
        }

        $query1 = []; $query2 = []; $query3Raw = '1=1'; $query4 = [];

        if(!$type) {
            $query1 = $isAuth ? [] : ['dan.category' => Notes::category_1, 'dan.classes_id' => $classesId];
        }
        if($type == Notes::category_1) {//老师上传
            $query1 = ['dan.category' => Notes::category_1, 'dan.create_id' => $admin['id']];
        }
        if($type == Notes::category_2) {//家长上传
            $query1 = ['dan.category' => Notes::category_2, 'dan.classes_id' => $classesId];
        }
        if($isAuth) {
            $query2 = $gradeId ? ['dc.grade_id' => $gradeId] : [];
            $query4 = $classesId ? ['dan.classes_id' => $classesId] : [];
        }
        $query5 = $realmId ? ['dan.dts_activity_realm_id' => $realmId] : [];
        $query6 = $labelId ? ['dan.dts_activity_label_id' => $labelId] : [];
        $query3Raw = $studentId ? 'FIND_IN_SET('.$studentId.',dan.student_ids) > 0' : '1=1';

        $list = Db::name('dts_activity_notes')->alias('dan')
        ->field('dan.id,dan.category,dan.observe_goal,FROM_UNIXTIME(dan.createtime,"%Y-%m-%d %H:%i") as createtime,GROUP_CONCAT(stu.avatar) as avatars,GROUP_CONCAT(stu.username) as usernames,ad.nickname,dar.name as darname,dal.name as dalname')
        ->join([
            ['admin ad', 'ad.id = dan.admin_id', 'left'],
            ['dts_student stu', 'FIND_IN_SET(stu.id,dan.student_ids)', 'left'],
            ['dts_classes dc', 'dc.id = dan.classes_id', 'left'],
            ['dts_activity_realm dar', 'dar.id = dan.dts_activity_realm_id', 'left'],
            ['dts_activity_label dal', 'dal.id = dan.dts_activity_label_id', 'left'],
        ])
        ->where(array_merge($query1, $query2, $query4, $query5, $query6))
        ->whereRaw($query3Raw)
        ->order('dan.createtime', 'desc')
        ->group('dan.id')
        ->paginate($pagesize, false, ['page' => $page]);
        
        $this->success('success', $list);
    }

    //活动小记详情
    public function activityNotesInfo() {

        $notesId = $this->request->get('notesId');

        $service = new \app\api\controller\Service;
        $list = $service->activityNotesInfo($notesId, 1);

        $this->success('success', $list);
    }

    //发布或编辑活动小记
    public function releaseActivityNotes() {

        $notesId = $this->request->post('notesId');
        $classesId = $this->request->post('classesId');
        $studentIds = $this->request->post('studentIds');
        $student_age = $this->request->post('student_age');
        $student_json = $this->request->post('student_json');
        $observe_site = $this->request->post('observe_site');
        $observe_time = $this->request->post('observe_time');
        $observe_goal = $this->request->post('observe_goal');
        $phenomenon = $this->request->post('phenomenon');
        $phenomenon_json = $this->request->post('phenomenon_json');
        $dts_activity_realm_id = $this->request->post('dts_activity_realm_id');
        $dts_activity_label_id = $this->request->post('dts_activity_label_id');
        $analysis = $this->request->post('analysis');
        $measure = $this->request->post('measure');

        if(!$classesId || !$studentIds || !$student_age || !$observe_site || !$observe_time || !$observe_goal || !$phenomenon ||
        !$dts_activity_realm_id || !$dts_activity_label_id || !$analysis || !$measure) {
            $this->error('请上传活动小记内容');
        }

        $admin = $this->auth->getAdmininfo();

        $data = [
            'classes_id' => $classesId, 'admin_id' => $admin['id'], 'student_ids' => $studentIds, 'student_age' => $student_age, 'student_json' => $student_json,
            'observe_site' => $observe_site, 'observe_time' => $observe_time, 'observe_goal' => $observe_goal,
            'phenomenon' => $phenomenon, 'phenomenon_json' => html_entity_decode($phenomenon_json), 'dts_activity_realm_id' => $dts_activity_realm_id, 
            'dts_activity_label_id' => $dts_activity_label_id, 'analysis' => $analysis, 'measure' => $measure, 'createtime' => time()
        ];

        if($notesId) {
            \app\admin\model\dts\activity\Notes::where('id', $notesId)->update($data);
        }else {
            $data['category'] = Notes::category_1;
            $data['create_id'] = $admin['id'];
            \app\admin\model\dts\activity\Notes::create($data);
        }

        $this->success('success');
    }

    //评价活动小记
    public function evaluateActivityNotes() {

        $notesId = $this->request->post('notesId');
        $content = $this->request->post('content');
        if(!$notesId || !$content) {
            $this->error('请提交评价内容');
        }

        $admin = $this->auth->getAdmininfo();
        $data = ['dts_activity_notes_id' => $notesId, 'content' => $content, 'admin_id' => $admin['id']];

        \app\admin\model\dts\activity\notes\Evaluate::create($data);

        $this->success('success');
    }
    
    //删除活动小记
    public function delActivityNotes() {
        $notesId = $this->request->post('notesId');
        if(!$notesId) {
            $this->error('请选择删除活动');
        }

        $notesModel = new \app\admin\model\dts\activity\Notes;
        $notesModel->where('id', $notesId)->delete();

        $this->success('success');
    }

    //资源管理
    public function resourceList() {

        $filename = $this->request->get('filename');
        $query1 = $filename ? ['filename' => ['LIKE', '%'.$filename.'%']] : [];
        $category = $this->request->get('category');
        $query2 = $category ? ['category' => $category] : [];
        $subclass = $this->request->get('subclass');
        $query3 = $subclass ? ['subclass' => $subclass] : [];

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = Db::name('attachment')->field('id,filename,filesize,mimetype,url,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i:%s") as createtime')->where(array_merge($query1, $query2, $query3))->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //删除资源
    public function delResource() {
        $fileIds = $this->request->post('fileIds/a');
        if(!$fileIds) {
            $this->error('请选择删除资源');
        }

        Db::name('attachment')->where('id', 'in', $fileIds)->delete();

        $this->success('success');
    }

    //新增或编辑资源父类型
    public function addOrEditConfigClassifyType() {

        $name = $this->request->post('name');
        $remark = $this->request->post('remark');
        if(!$name) {
            $this->error('请提交资源类型信息');
        }

        $configId = $this->request->post('configId');
        $data = ['name' => $name, 'remark' => $remark];

        __db(function() use($configId, $data) {
            
            if($configId) {
                Db::name('dts_config_classify_type')->where('id',  $configId)->update($data);
            }else {
                model('model/dts/config/classify/type')->create($data);
            }
    
            $configData = [];
            $list = Db::name('dts_config_classify_type')->select();
            foreach($list as $item) {
                $configData[$item['id']] = $item['name'];
            }
    
            $configModel = new \app\common\model\Config;
            $configModel->where('id', 18)->update(['value' => json_encode($configData, JSON_UNESCAPED_UNICODE)]);
    
            $configModel::refreshFile();
        });

        $this->success('success');
    }

    //新增资源子类型
    public function addOrEditConfigClassifyLabel() {
       
        $typeId = $this->request->post('typeId');
        $name = $this->request->post('name');
        $visible_admin_ids = $this->request->post('visible_admin_ids');
        $visible_admin_json = $this->request->post('visible_admin_json');
        $remark = $this->request->post('remark');
        if(!$typeId || !$name) {
            $this->error('请提交资源类型信息');
        }

        $data = ['config_classify_type_id' => $typeId, 'name' => $name, 'visible_admin_ids' => null, 'visible_admin_json' => null, 'remark' => $remark];
        if($visible_admin_ids) {
            $data['visible_admin_ids'] = $visible_admin_ids;
        }
        if($visible_admin_json) {
            $data['visible_admin_json'] = $visible_admin_json;
        }

        $configId = $this->request->post('configId');
        if($configId) {
            Db::name('dts_config_classify_label')->where('id',  $configId)->update($data);
        }else {
            model('model/dts/config/classify/label')->create($data);
        }

        $this->success('success');
    }

    //删除资源类型
    public function delConfigClassify() {

        $category = $this->request->post('category');
        $configId = $this->request->post('configId');
        if(!$category || !$configId) {
            $this->error('请选择删除类型');
        }

        $num = Db::name('attachment')->where('subclass', $configId)->count(1);
        if($num) {
            $this->error('当前资源类型有所属文件');
        }

        Db::name('dts_config_classify_label')->where('id', $configId)->delete();

        $this->success('success');
    }

    //主题文档
    public function themedocumentList() {

        $name = $this->request->get('name');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $admin = $this->auth->getAdmininfo();
        $query = $name ? ['name' => ['LIKE', '%'.$name.'%']] : [];

        $list = Db::name('dts_themedocument')
        ->field('id,name,reason,createby,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i") as createtime')
        ->where($query)
        ->whereRaw('FIND_IN_SET('.$admin['id'].',visible_admin_ids) > 0 OR visible_admin_ids is NULL')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //主题文档详情
    public function themedocumentInfo() {
        $themeId = $this->request->get('themeId', 0);

        $info = Db::name('dts_themedocument')->alias('dt')
        ->field('dt.*,GROUP_CONCAT(DISTINCT admin.nickname) as visible_admin_names')
        ->join('admin admin', 'FIND_IN_SET(admin.id,dt.visible_admin_ids)', 'left')
        ->where('dt.id', $themeId)
        ->find();

        $this->success('success', $info);
    }

    //新增或编辑主题文档
    public function addOrEditThemedocument() {

        $themeId = $this->request->post('themeId');
        $name = $this->request->post('name');
        $reason = $this->request->post('reason');
        $content = $this->request->post('content/a');
        $analysis = $this->request->post('analysis');
        $objectives = $this->request->post('objectives');
        $framework_files = $this->request->post('framework_files');
        $framework_files_json = $this->request->post('framework_files_json');
        $environment_files = $this->request->post('environment_files');
        $environment_files_json = $this->request->post('environment_files_json');
        $activity_cases = $this->request->post('activity_cases/a');
        $reflections = $this->request->post('reflections');
        $visible_admin_ids = $this->request->post('visible_admin_ids');
        $visible_admin_ids_json = $this->request->post('visible_admin_ids_json');

        if(!$name || !$reason || !$content) {
            $this->error('请提交文档信息');
        }

        $admin = $this->auth->getAdmininfo();
        $data = [
            'name' => $name, 'reason' => $reason, 'content' => $content ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content, 'analysis' => $analysis,
            'objectives' => $objectives, 'framework_files' => $framework_files, 'environment_files' => $environment_files,
            'activity_cases' => $activity_cases ? json_encode($activity_cases, JSON_UNESCAPED_UNICODE) : $activity_cases,
            'reflections' => $reflections, 'createby' => $admin['nickname'],
            'visible_admin_ids' => null, 'visible_admin_ids_json' => null
        ];

        if($visible_admin_ids) {
            $data['visible_admin_ids'] = $visible_admin_ids;
        }
        if($visible_admin_ids_json) {
            $data['visible_admin_ids_json'] = $visible_admin_ids_json;
        }

        if($framework_files_json) {
            $data['framework_files_json'] = html_entity_decode($framework_files_json);
        }
        if($environment_files_json) {
            $data['environment_files_json'] = html_entity_decode($environment_files_json);
        }

        if($themeId) {
            Db::name('dts_themedocument')->where('id', $themeId)->update($data);
        }else {
            model('model/dts/themedocument')->create($data);
        }

        $this->success('success');
    }

    //删除主题文档
    public function delThemedocument() {

        $themeId = $this->request->post('themeId');
        if(!$themeId) {
            $this->error('请选择删除的文档');
        }

        Db::name('dts_themedocument')->where('id', $themeId)->delete();

        $this->success('success');
    }
}